# -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
本文件实现了一个完整的demo
"""

from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from bottle import route, run, template, request
from PIL import Image, ImageFont, ImageDraw


import multiprocessing
import sys
import base64
import urllib.parse
import numpy as np
import cv2
import logging
import json

_model_dir = '/opt/py/baidu/RES/'
_test_img = '/opt/py/baidu/bottle/1562679047195.jpg'
_test_round = 1


@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)



@route('/hello2',  method='POST')
def test2():
    aaa = request.forms.get('image')
    print(aaa)
    a1 = urllib.parse.unquote(aaa)
    a3 = base64.b64decode(a1.encode('utf-8'))
    a2 = str(a3,'utf-8')
    print("BASE64解密aaaaaaaaaaaaaaaa串（UTF-8）:\n",a2)
    aaa = json.loads(a2)
    print(aaa)
    filename = request.forms.get('filename')
    outputFilepath = request.forms.get('outputFilepath')
    
    print(filename)
    print(outputFilepath)

    imgcv = cv2.imread(filename)

    (H, W, C) = imgcv.shape
    print(H)

    fontWidth = 20
    fontSize = 30

    if(H > 480):
        fontWidth = 40
        fontSize = 40

    cv2_im = cv2.cvtColor(imgcv,cv2.COLOR_BGR2RGB)
    pil_im = Image.fromarray(cv2_im)
    draw = ImageDraw.Draw(pil_im)
    font = ImageFont.truetype("simhei.ttf",fontWidth,encoding="utf-8")
    
    for r in aaa:
        x1 = r['x1']
        y1 = r['y1']
        x2 = r['x2']
        y2 = r['y2']
        score = 1
        if ('score' in r) :
            score = r['score']
        bname = r['label']
        width = len(bname) * fontSize
        if score == 1 :
            draw.rectangle([x1, y1, x2, y2],outline='green',width=4)
            draw.rectangle([x1, y1, x1 + width, y1 + fontWidth], 'blue', 'green')
            draw.text((x1, y1), bname, (0, 255, 0), font=font)
        else :
            draw.rectangle([x1, y1, x2, y2],outline='red',width=4)
            draw.rectangle([x1, y1, x1 + width, y1 + fontWidth], 'blue', 'red')
            draw.text((x1, y1), bname, 'red', font=font)


    
    cv2_text_im = cv2.cvtColor(np.array(pil_im),cv2.COLOR_BGR2RGB)
    cv2.imwrite(outputFilepath, cv2_text_im)

    return 'ok'


@route('/hello3',  method='POST')
def test():

    """单进程"""
    line_color = (125, 175, 75)

    print(request.forms.get('image'))
    aaa = [{"x1":712,"y1":0,"x2":1246,"y2":505,"label":"aa"},{"x1":642,"y1":471,"x2":1190,"y2":1014,"label":"aa"},{"x1":116,"y1":415,"x2":655,"y2":981,"label":"aa"},{"x1":174,"y1":0,"x2":715,"y2":438,"label":"aa"}]
    aaa = request.forms.get('image')
    aaa = [{"x1":311,"y1":191,"x2":533,"y2":416,"label":"测试"}]
    filename = request.forms.get('filename')
    outputFilepath = request.forms.get('outputFilepath')

    img = cv2.imread(filename)
    for r in aaa:
        x1 = r['x1']
        y1 = r['y1']
        x2 = r['x2']
        y2 = r['y2']
        cv2.rectangle(img, (x1, y1), (x2, y2), line_color, 2)
        cv2.putText(
            img=img, text=r['label'], org=(x1, y1),
            fontFace=cv2.FONT_HERSHEY_COMPLEX, fontScale=2, color=line_color, thickness=5
        )
        print(r)

    cv2.imwrite(outputFilepath, img)

    return 'ok'



@route('/hello4',  method='POST')
def hello4():



    aaa = request.forms.get('image')
    print(aaa)

    ab = urllib.parse.unquote(aaa)
    print(ab)

    fff = base64.b64decode(ab)
    print(fff)

    bbb = base64.b64encode('测试'.encode('utf-8'))
    ddd = base64.b64encode('测试'.encode('gbk'))
    print(bbb)
    print(ddd)
    ccc = base64.b64decode(bbb)
    eee = base64.b64decode(ddd)
    print(ccc)
    print(eee)

    base64_encrypt = base64.b64encode("测试".encode('utf-8'))
    print("BASE64加密串:\n"+str(base64_encrypt,'utf-8'))

    base64_decrypt = base64.b64decode("5rWL6K+V".encode('utf-8'))
    print("BASE64解密串（UTF-8）:\n",str(base64_decrypt,'utf-8'))


    return 'ok'



@route('/hello5',  method='POST')
def hello5():

    aaa = request.forms.get('image')

    a1 = urllib.parse.unquote(aaa)

    a3 = base64.b64decode(a1.encode('utf-8'))

    a2 = str(a3,'utf-8')
    print("BASE64解密aaaaaaaaaaaaaaaa串（UTF-8）:\n",a2)

    result=json.dumps(a2)
    print(result)
    print(type(result))
    a5 = json.loads(a2)
    print(a5)
    print(type(a5))
    print(a5[0]['x1'])

    for r in a5:
        print(r['x1'])

    return 'ok'
#binguo2====
#run(host='172.17.0.16', port=8082)

#newbinguo===
run(host='172.17.0.5', port=8082)

#beijing===
#run(host='172.21.0.3', port=8082)

# def test_multi_ncs():
#     """同时使用多个设备"""
#     q = multiprocessing.Queue(maxsize=100)
#
#     img = cv2.imread(_test_img)
#
#     def _task(i):
#         print("Process %d started" % i)
#         pred = edge.Program()
#         pred.init(model_dir=_model_dir, device=edge.Device.CPU, engine=edge.Engine.PADDLE_FLUID)
#
#         while True:
#             try:
#                 img = q.get(block=True, timeout=1)
#                 print("Process", i, pred.infer_image(img))
#             except Exception as e:
#                 break
#
#         pred.close()
#
#     p1 = multiprocessing.Process(target=_task, args=[1])
#     p2 = multiprocessing.Process(target=_task, args=[2])
#
#     p1.start()
#     p2.start()
#
#     for i in range(_test_round):
#         q.put(img)
#
#     p1.join()
#     p2.join()


#if __name__ == '__main__':
#    test()


